import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2cpick/b2cpickcategoryscreen.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

class B2CPickOBLPNScreen extends StatelessWidget {
  B2CPickBean b2cPickBean;

  B2CPickOBLPNScreen({this.b2cPickBean});

  @override
  Widget build(BuildContext context) {
    return B2CPickOBLPNScreenPage(b2cPickBean: b2cPickBean);
  }
}

class B2CPickOBLPNScreenPage extends StatefulWidget {
  B2CPickBean b2cPickBean;

  B2CPickOBLPNScreenPage({this.b2cPickBean});

  @override
  _B2CPickOBLPNScreenPageState createState() => _B2CPickOBLPNScreenPageState(b2cPickBean: b2cPickBean);
}

class _B2CPickOBLPNScreenPageState extends BaseState<B2CPickOBLPNScreenPage> {
  B2CPickBean b2cPickBean;

  _B2CPickOBLPNScreenPageState({this.b2cPickBean});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<ChildPick> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pickup:OBLPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        data = b2cPickBean.childPicks;
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only( top: 0,),
            child: Row(
              children: [
                Text(
                  "Job    No: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.isBool(b2cPickBean.isNoneLocation)?"NONE Location":Utils.getStringisEmpty(b2cPickBean.pickNo),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),

          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 10),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  CheckLpn();
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        CheckLpn();
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "input outbound lpn",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Text(
            "Selected Pending Jobs: ",
            style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
          ),
          SizedBox(height: 5,),
          Expanded(child: setListView())

        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        ChildPick childPick = data[index];
        if (childPick.isChoose == null) {
          childPick.isChoose = false;
        }
        return Row(
          children: [
            Expanded(
                flex: 1,
                child: Text(
                  "${childPick.pickNo} (${childPick.completeQty}/${childPick.totalQty})",
                  style: MyAppTheme.text,
                )),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    // if (Utils.isEmpty(strDate)) {
    //   Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    PickupPol3CategoryQr pickupPol3CategoryQr = new PickupPol3CategoryQr();
    pickupPol3CategoryQr.pickId = b2cPickBean.id == null ? null : '${b2cPickBean.id}';
    List<int> pickChildIds = new List();
    for (ChildPick childPick in b2cPickBean.childPicks) {
    pickChildIds.add(childPick.id);
    }
    pickupPol3CategoryQr.pickChildIds = pickChildIds;
    var json = jsonEncode(pickupPol3CategoryQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_queryPendingPicks, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        List<B2CPickBean> B2CPickBeans = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => B2CPickBean.fromJson(userJson)).toList());
        if (B2CPickBeans == null) {
          return;
        }
        if (B2CPickBeans.length == 0) {
          return;
        }
        var b2cPickBean = B2CPickBeans[0];

        this.b2cPickBean.totalQty = b2cPickBean.totalQty;
        this.b2cPickBean.completeQty = b2cPickBean.completeQty;
        this.b2cPickBean.childPicks = b2cPickBean.childPicks;
        data = B2CPickBeans[0].childPicks;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  void CheckLpn() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "Check...");
    } catch (e) {
      e.toString();
    }
    PickObLpn pickObLpn = new PickObLpn();
    pickObLpn.pickId = b2cPickBean.id;
    pickObLpn.obLpn = textEditingController.text;
    var json = jsonEncode(pickObLpn);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_checkObLpn, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        PickupPol3OBLPN pickupPol3OBLPN = PickupPol3OBLPN.fromJson(baseResponse.data);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => B2CPickCategoryScreen(b2cPickBean: b2cPickBean,pickupPol3OBLPN:pickupPol3OBLPN)),
        ).then((value) => {getTallyContainerNo()});
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
